<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\middleware\Auth;
use app\BaseController;
use app\common\model\Project\Order as OrderModel;
use think\facade\Db;
use think\facade\View;
use app\common\model\User\Record as RecordModel;
use app\common\validate\User\Record as RecordValidate;
use think\exception\ValidateException;

class ProjectOrder extends BaseController
{
    protected $middleware = [
        Auth::class
    ];

    public function index()
    {
        $nav_title = [
            'nav_title' => '预约管理',
            'title' => '预约订单'
        ];

        // 接收查询字段
        $SearchField = $this->request->param('search_field','name');

        $keyword = $this->request->param('keyword','');

        $where = [];

        if(!empty($SearchField) && !empty($keyword))
        {
            $where[] = [$SearchField,'like',"%$keyword%"];
        }else{
            $keyword = '请输入相应的内容';
        }

        // 查询数据
        $OrderList = OrderModel::hasWhere('user',[['deletetime','EXP',Db::raw('is null')]])->hasWhere('project')->hasWhere('address')->where($where)->paginate(['list_rows' => 5,'query' => request()->param()]);

        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $num = ($OrderList->currentPage() - 1) * $OrderList->listRows();
        
        return View::fetch('',[
            'nav_title' => $nav_title,
            'OrderList' => $OrderList,
            'num' => $num,
            'SearchField' => $SearchField,
            'keyword' => $keyword
        ]);
    }

    // 报价
    public function offer()
    {
        if($this->request->isAjax())
        {
            $price = $this->request->param('price','');

            $projectid = $this->request->param('projectid');
            

            $order = OrderModel::find($projectid);

            if(!$order)
            {
                $this->error('该预约订单不存在');
            }

            $data = [
                'price' => $price,
                'status' => 1
            ];

            $result = $order->save($data);

            if($result !== true)
            {
                $this->error('报价失败');
            }else{
                $this->success('报价成功');
            }
        }
    }

    public function recycle()
    {
        $nav_title = [
            'nav_title' => '预约管理',
            'title' => '回收站'
        ];

        // 接收查询字段
        $SearchField = $this->request->param('search_field','name');

        $keyword = $this->request->param('keyword','');

        $where = [];

        if(!empty($SearchField) && !empty($keyword))
        {
            $where[] = [$SearchField,'like',"%$keyword%"];
        }else{
            $keyword = '请输入相应的内容';
        }

        // 查询数据
        $OrderList = OrderModel::onlyTrashed()->hasWhere('user',[['deletetime','EXP',Db::raw('is null')]])->hasWhere('project')->hasWhere('address')->where($where)->paginate(['list_rows' => 5,'query' => request()->param()]);

        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $num = ($OrderList->currentPage() - 1) * $OrderList->listRows();
        
        return View::fetch('',[
            'nav_title' => $nav_title,
            'OrderList' => $OrderList,
            'num' => $num,
            'SearchField' => $SearchField,
            'keyword' => $keyword
        ]);
    }

    public function revoke()
    {
        if($this->request->isAjax())
        {
            $aciton = $this->request->param('action');

            $projectid = $this->request->param('projectid');

            // 查询数据是否存在
            $project = OrderModel::find($projectid);

            if(!$project)
            {
                $this->error('该订单不存在');
            }

            // 开启事务
            RecordModel::startTrans();
            OrderModel::startTrans();

            $record = new RecordModel();

            // 通过撤销
            if($aciton == 'success')
            {
                $OrderData = [
                    'status' => -1
                ];

                $result = $project->save($OrderData);

                if($result !== true)
                {
                    $this->error('操作失败');
                }

                $RecordData = [
                    'userid' => $project['userid'],
                    'point' => $project['price'],
                    'content' => "您的预约订单【{$project['content']}】，申请撤销成功，将退款{$project['price']}元",
                    'state' => (Int)-1
                ];

                $RecordStatus = $record->save($RecordData);

                if($RecordStatus !== true)
                {
                    OrderModel::rollback();
                    $this->error('新增消费记录失败');
                }

                if($RecordStatus !== true || $result !== true)
                {
                    OrderModel::rollback();
                    RecordModel::rollback();
                    $this->error('操作失败');
                }else{
                    OrderModel::commit();
                    RecordModel::commit();
                    $this->success('撤销通过');
                }


            }else{
                $OrderData = [
                    'status' => -3
                ];

                $result = $project->save($OrderData);

                if($result !== true)
                {
                    $this->error('操作失败');
                }

                $RecordData = [
                    'userid' => $project['userid'],
                    'point' => $project['price'],
                    'content' => "您的预约订单【{$project['content']}】，申请撤销失败，将联系您协商",
                    'state' => -1
                ];

                $RecordStatus = $record->save($RecordData);

                if($RecordStatus !== true)
                {
                    OrderModel::rollback();
                    $this->error('新增消费记录失败');
                }

                if($RecordStatus !== true || $result !== true)
                {
                    OrderModel::rollback();
                    RecordModel::rollback();
                    $this->error('操作失败');
                }else{
                    OrderModel::commit();
                    RecordModel::commit();
                    $this->success('撤销不通过');
                }
            }
        }
    }

    // 恢复
    public function recovery()
    {
        if($this->request->isPost())
        {
            $postid = $this->request->param('postid');

            if(empty($postid))
            {
                $this->error('请选择要恢复的记录');
            }


            if(is_array($postid))
            {

                $PostList = OrderModel::onlyTrashed()->whereIn('id',$postid)->column('id');

                $NotId = '';

                foreach($postid as $item)
                {
                    if(!in_array($item,$PostList))
                    {
                        $NotId .= $item . ',';
                    }
                }

                $NotId = rtrim($NotId,',');

                if(!empty($NotId))
                {
                    $this->error("ID：{$NotId}不存在，请重新选择");
                }

                $result = OrderModel::onlyTrashed()->whereIn('id',$postid)->update(['deletetime' => null]);

                

                if($result != true)
                {
                    $this->error('批量恢复失败');
                }else{
                    $this->success('批量恢复成功');
                }

            }else{
                $post = OrderModel::onlyTrashed()->find($postid);

                if(!$post)
                {
                    $this->error('要恢复的的记录不存在');
                }

                // 还原
                $result = $post->restore();

                if($result !== true)
                {
                    $this->error('恢复失败');
                }else{
                    $this->success('恢复成功');
                }
            }
        }
    }

    public function del()
    {
        if($this->request->isAjax())
        {
            $projectid = $this->request->param('projectid');

            $action = $this->request->param('action');

            if(empty($projectid))
            {
                $this->error('请选择订单');
            }

            if(is_array($projectid))
            {
                

                if($action == 'delete')
                {
                    $OrderList = OrderModel::onlyTrashed()->whereIn('id',$projectid)->column('id');
                }else{
                    $OrderList = OrderModel::whereIn('id',$projectid)->column('id');

                }

                $NotId = '';

                foreach($projectid as $item)
                {
                    if(!in_array($item,$OrderList))
                    {
                        $NotId .= $item . ',';
                    }
                }

                $NotId = rtrim($NotId,',');

                if(!empty($NotId))
                {
                    $this->error("ID：{$NotId}不存在，请重新选择");
                }

                if($action == 'delete')
                {
                    $result = OrderModel::destroy($projectid,true);
                }else{
                    // 软删除
                    $result = OrderModel::destroy($projectid);
                }

                if($result !== true)
                {
                    $this->error('批量删除失败');
                }else{
                    $this->success('批量删除成功');
                }
                

            }else{
                // 单条删除
                if($action == 'delete')
                {
                    $Order = OrderModel::onlyTrashed()->find($projectid);
                }else{
                    // 软删除
                    $Order = OrderModel::find($projectid);
                }
                

                if(!$Order)
                {
                    $this->error('该订单不存在，无法删除');
                }

                if($action == 'delete')
                {
                    $result = OrderModel::destroy($projectid,true);
                }else{
                    // 软删除
                    $result = OrderModel::destroy($projectid);
                }

                if($result !== true)
                {
                    $this->error('删除失败');
                }else{
                    $this->success('删除成功');
                }

            }
        }
    }

    public function repair()
    {
        $nav_title = [
            'nav_title' => '预约管理',
            'title' => '预约进度'
        ];

        $projectid = $this->request->param('projectid');

        $project = OrderModel::find($projectid);

        return View::fetch('',[
            'nav_title' => $nav_title,
            'project' => $project
        ]);
    }
}
